package pri.zxx.webdemo.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import pri.zxx.webdemo.utils.MDCUtil;
import pri.zxx.webdemo.utils.TokenHolder;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author wangn <15124178@qq.com> 2020/7/15
 */
@Component
@ConditionalOnProperty(value = "custom.log.trace.enable", matchIfMissing = true)
@Slf4j
public class TraceLogInterceptor implements CustomHandleInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) {
        response.addHeader(MDCUtil.REQUEST_ID, MDCUtil.initRequestId());
        MDC.clear();
        TokenHolder.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {

        TokenHolder.add(request.getHeader("token"));
        String header = request.getHeader(MDCUtil.REQUEST_ID);
        if (StringUtils.hasText(header)) {
            MDCUtil.setRequestId(header);
        } else {
            MDCUtil.initRequestId();
        }
        return true;
    }

}
